
#include "at_protocol.h"
#include <string.h>

#define isa(d) ('A'==d || 'a'==d)
#define ist(d) ('T'==d || 't'==d)
#define isend(d) ('\r'==d || '\n'==d )

AT_PARSE_STATUS at_parse(unsigned char data, AT* at, AT_PARSE_STATUS* status){
	
	if( AT_PARSE_STATUS_NONE==*status && isa(data) ){
		*status = AT_PARSE_STATUS_A;
		at->data_count = 0;
		at->at_data[at->data_count] = data;
		++at->data_count;
	}else if( AT_PARSE_STATUS_A==*status && ist(data) ){
		*status = AT_PARSE_STATUS_T;
		at->at_data[at->data_count] = data;
		++at->data_count;
	}else if( AT_PARSE_STATUS_T==*status && data=='+' ){
		*status = AT_PARSE_STATUS_ADD;
		at->at_data[at->data_count] = data;
		++at->data_count;
	}else if( AT_PARSE_STATUS_ADD==*status ){
		
		if(at->data_count>59){
			*status = AT_PARSE_STATUS_NONE;
			return *status;
		}
		
		if( isend(data) ){
			*status = AT_PARSE_STATUS_END;
			at->at_data[at->data_count] = data;
			at->at_data[at->data_count+1] = '\0';
			*status = AT_PARSE_STATUS_NONE;
			return AT_PARSE_STATUS_END;			
		}
		
		at->at_data[at->data_count] = data;
		++at->data_count;
	}else *status = AT_PARSE_STATUS_NONE;
	
	return *status; 	
}


unsigned char at_have_header(const AT* at){
	char header[4] = "AT+";
	
	strncpy(header, (const char*)at->at_data, 3);
	
	strtolwr(header);
	
	if(strcmp(header, "at+")==0 || strcmp(header, "AT+")==0) return 1;
	else return 0;
}


char* at_get_type(const AT* at, char* type){
	char* s = strstr((const char*)at->at_data, "+");
	char* e = strstr((const char*)at->at_data, "=");
	char* ee = strstr((const char*)at->at_data, "?");
	char* pp, *pd = type;
	unsigned char len = 0;
	
	if(e==(void*)0 && ee==(void*)0) return (void*)0;
	else if(e==(void*)0 && ee!=(void*)0) e = ee;
	else if(e!=(void*)0 && ee!=(void*)0){
		if(e>ee) e=ee;
	}
	
	for( pp=s+1; pp!=e; ){
		*pd = *pp;
		++pp;
		++pd;
		++len;
		if(len>7) return (void*)0;
	}
	
	*pd = '\0';
	
	return type;
}


char* at_get_data(AT* at, char* data){
	char* s = strstr((const char*)at->at_data, "=");
	char* e = strstr((const char*)at->at_data, "\r");
	char* ee = strstr((const char*)at->at_data, "\n");
	char* pp, *pd = data;
	unsigned char len = 0;
	
	if(e==(void*)0 && ee==(void*)0) return (void*)0;
	else if(e==(void*)0 && ee!=(void*)0) e = ee;
	else if(e!=(void*)0 && ee!=(void*)0){
		if(e>ee) e=ee;
	}
	
	for( pp=s+1; pp!=e; ){
		*pd = *pp;
		++pp;
		++pd;
		++len;
		if(len>50) return (void*)0;
	}
	
	*pd = '\0';
	
	return data;
}

char* strtolwr(char* str){
  char *pc = str;
	
	if((void*)0==str) return (void*)0;
	
	while(*pc!='\0'){
		if(*pc>='A' && *pc<='Z') *pc = 'a'+*pc-'A';
		++pc;
	}
	
	return str;
}

unsigned char is_num(const char* str){
	const char* p = str;
	while(*p!='\0'){
		if(*p>='0' && *p<='9'){
			++p;
			continue;
		}else return 0;
	}
	return 1;
}
